package com.zyplayer.data.screen.controller;

import cn.hutool.crypto.asymmetric.RSA;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyplayer.data.screen.framework.exception.ConfirmException;
import com.zyplayer.data.screen.framework.json.DocResponseJson;
import com.zyplayer.data.screen.framework.json.ResponseJson;
import com.zyplayer.data.screen.repository.manage.entity.PrivateKey;
import com.zyplayer.data.screen.service.manage.PrivateKeyService;
import com.zyplayer.data.screen.utils.RSAUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/secure")
public class OpenSecureController {
	
	@Resource
	PrivateKeyService privateKeyService;
	
	@PostMapping("/create")
	public ResponseJson<Object> create(String publicKey) {
		QueryWrapper<PrivateKey> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("yn", 1);
		PrivateKey privateKey = privateKeyService.getOne(queryWrapper);
		// 没有key则新建
		if (privateKey == null) {
			RSA rsa = new RSA();
			PrivateKey privateKeyUp = new PrivateKey();
			privateKeyUp.setCreateTime(new Date());
			privateKeyUp.setPrivateKey(rsa.getPrivateKeyBase64());
			privateKeyUp.setPublicKey(rsa.getPublicKeyBase64());
			privateKeyUp.setYn(1);
			privateKeyService.save(privateKeyUp);
			return DocResponseJson.ok(privateKeyUp.getPublicKey());
		}
		// 有了则校验
		if (!Objects.equals(publicKey, privateKey.getPublicKey())) {
			return DocResponseJson.error("公钥错误");
		}
		return DocResponseJson.ok(publicKey);
	}
}
